package cn.akwangl.future;

import java.util.concurrent.*;

/**
 * 任务超时demo.
 * 1. {@link Future#cancel(boolean)} ture:任务响应{@link InterruptedException}中断,false:任务不响应
 *
 * @author 阿坤同学
 * @date 2022/12/20 18:53
 */
public class Timeout {

    public static void main(String[] args) {
        ExecutorService executorService = Executors.newFixedThreadPool(2);

        // 直接抛出异常
        Callable<Ad> task = () -> {
            try {
                Thread.sleep(3000L);
                Ad ad = new Ad("旅游哪家强？找某程");
                return ad;
            } catch (InterruptedException e) {
                System.out.println("响应中断...");
                return new Ad("超时被中断的广告");
            }
        };

        Future<Ad> future = executorService.submit(task);
        Ad ad = null;
        try {
            ad = future.get(2, TimeUnit.SECONDS);
        } catch (TimeoutException e) {
            System.out.println("获取广告超时");

            if (!future.isDone()) {
                boolean cancel = future.cancel(true);
                System.out.println("cancel 的结果:" + cancel);
            }
            ad = new Ad("超时默认的广告");
        } catch (ExecutionException e) {
            System.out.println("ExecutionException 发生异常");
            e.printStackTrace();
        } catch (InterruptedException e) {
            System.out.println("InterruptedException 发生异常");
            e.printStackTrace();
        } finally {
            executorService.shutdown();
        }

        System.out.println(ad);
    }


    static class Ad {
        private String name;

        public Ad(String name) {
            this.name = name;
        }

        public String getName() {
            return name;
        }

        public void setName(String name) {
            this.name = name;
        }

        @Override
        public String toString() {
            return "Ad{" + "name='" + name + '\'' + '}';
        }
    }
}
